package com.educate.handler;


import cn.hutool.json.JSONUtil;
import com.educate.pojo.response.ErrorResult;
import com.educate.pojo.response.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author xiongyu
 * @date 2021/8/1 23:27
 */
@ControllerAdvice(basePackages = "com")
@Slf4j
public class ResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(o == null) {
            return JSONUtil.toJsonStr(ResultBean.success(null));
          }

        if (o instanceof ErrorResult) {
            ErrorResult result = (ErrorResult) o;
            return ResultBean.fail(result.getStatus(), result.getMessage());
        }else if (o instanceof String) {
            return JSONUtil.toJsonStr(ResultBean.success(o));
        }

        return ResultBean.success(o);
    }
}
